<template>
  <a-spin :spinning="loading">
    <!--  折叠面板  -->
    <a-collapse v-model:activeKey="activeKey" ghost>
      <a-collapse-panel key="1">
        <template #header>
          <span class="title">1、录入退款金额</span>
        </template>
        <a-form
            ref="formRef"
            :model="formState"
            :rules="rules"
        >
          <a-form-item ref="orderId" label="订单号" name="orderId">
            <a-input-search style="width: 200px" v-model:value="formState.orderId" @search="init"/>
          </a-form-item>
        </a-form>
        <div class="title">订单数据</div>
        <a-descriptions :column="3" style="margin-top: 10px">
          <a-descriptions-item label="支付流水">{{ orderData.paymentNo }}</a-descriptions-item>
          <a-descriptions-item label="支付平台">{{ orderData.platform }}</a-descriptions-item>
          <a-descriptions-item label="下单时间">{{orderData.createdAtGmt}}</a-descriptions-item>
        </a-descriptions>
        <common-table
            :columns="firstColumns"
            :dataSource="firstDataList"
            :scroll="{ x: 'max-content' }"
        >
        </common-table>
        <!-- tabs页面 -->
        <a-tabs v-model:activeKey="tabKey" style="margin-top: 10px">
          <a-tab-pane key="1" tab="sku明细">
            <el-table :data="tableData"
                      style="width: 100%"
                      @selection-change="handleSelectionChange"
                      :header-cell-style="headerCellStyle">
                <el-table-column type="selection" width="55" />
                <el-table-column label="订单数据" align="center">
                  <el-table-column align="center" prop="productSkuItem" label="平台sku" width="140">
                    <template #default="{ row }">
                      {{row.productSkuItem.sku + "*" + row.productSkuItem.qtyOrdered}}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" prop="priceItem" label="售卖价/优惠价" width="120">
                    <template #default="{ row }">
                      {{row.priceItem.price + "/" +row.priceItem.rowDiscount}}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" prop="serviceItem" label="服务等级" width="120">
                    <template #default="{ row }">
                      <span>{{row.serviceItem.deliveryAmount}} </span>
                      <br>
                      <span>(剩余{{row.serviceItem.serviceRemaining}})</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" prop="outputItem" label="税金" width="120">
                    <template #default="{ row }">
                      <div v-if="firstDataList.site == 'CA'">
                        <div>联邦税: {{row.outputItem.countryTax}}</div>
                        <div>剩余: {{row.outputItem.federalTaxRemaining}}</div>
                      </div>
                      <div v-if="!'EU,AU,GB'.includes(firstDataList.site)">
                        <div>省税: {{row.outputItem.regionTax}}</div>
                        <div>剩余: {{row.outputItem.provincialTaxRemaining}}</div>
                      </div>
                      <div v-if="'EU,AU,GB'.includes(firstDataList.site)">
                        <div>销项: {{row.outputItem.outputVat}}</div>
                        <div>剩余: {{row.outputItem.outputVatRemaining}}</div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" prop="settlementAmountItem" label="结算金额（不含税）" width="120">
                    <template #default="{ row }">
                      <div>{{row.settlementAmountItem.rowGrand}}</div>
                      <div>(剩余{{row.settlementAmountItem.skuRemaining}})</div>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" prop="refundItem" label="历史退款总金额/剩余可退总金额" width="150">
                    <template #default="{ row }">
                      <span>{{ row.refundItem.totalRefund }}/{{row.refundItem.totalRemaining}}</span>
                    </template>
                  </el-table-column>
                </el-table-column>
              <el-table-column label="登记数据" align="center" label-class-name="registration">
                <el-table-column align="center" prop="custom" label="仓库sku&物流单号&数量" width="450">
                  <template #default="{ row,$index }">
                    <div style="display: flex;margin-bottom: 5px" v-for="(item,index) in row.packageList">
                      <a-auto-complete
                          v-model:value="item.warehouse"
                          :disabled="row.disabled"
                          :options="row.skuOptions"
                          style="width: 150px"
                          placeholder="仓库sku"
                          @select="(value)=>onSelect(value, row)"
                      />
                      <a-auto-complete
                          v-model:value="item.saleOrderCode"
                          :disabled="row.disabled"
                          placeholder="物流单号"
                          :options="row.saleOrderOptions"
                          style="width: 150px"
                      />
                      <a-input-number :min="0" style="width: 150px" :disabled="row.disabled" v-model:value="item.qty" />
                        <PlusOutlined style="margin-left: 10px;color: #17a507" @click="addInput($index)"/>
                        <DeleteOutlined style="margin-left: 10px;color: #ba0b16" @click="deleteInput($index,index)" v-if="row.packageList.length>1"/>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="replaceSku" label="换货sku" width="170">
                  <template #default="{ row }">
                    <a-textarea v-model:value="row.replaceSku" :disabled="row.disabled"/>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="skuRefund" label="退款sku金额" width="170">
                  <template #default="{ row }">
                    <a-input-number :max="row.settlementAmountItem.rowGrand" @change="changeNum(row)" :precision="4" :min="0" style="width: 100px" :disabled="row.disabled" v-model:value="row.skuRefund" />
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="serviceRefund" label="退款服务费" width="170">
                  <template #default="{ row }">
                    <a-input-number @change="changeNum(row)" :precision="4" :min="0" style="width: 100px" :disabled="row.disabled" v-model:value="row.serviceRefund" />
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column label="系统计算" align="center">
                <el-table-column align="center" prop="restTaxItem" label="退款税金" width="120">
                  <template #default="{ row }">
                    <div v-if="firstDataList.site == 'CA'">
                      <span class="label">联邦税:</span>
                      <span>{{row.restTaxItem.federalTaxRefund}} </span>
                    </div>
                    <div v-if="!'EU,AU,GB'.includes(firstDataList.site)">
                      <span class="label">省税:</span>
                      <span>{{row.restTaxItem.provincialTaxRefund}} </span>
                    </div>
                    <div v-if="'EU,AU,GB'.includes(firstDataList.site)">
                      <span class="label">销项:</span>
                      <span>{{row.restTaxItem.outputVatRefund}} </span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="totalNoTaxRefund" label="实际退款金额（不含税）" width="120" />
                <el-table-column align="center" prop="totalTaxRefund" label="实际退款金额（含税）" width="120" />
              </el-table-column>
            </el-table>
            <common-table
                :columns="columns"
                :dataSource="paramsList"
                :scroll="{ x: 'max-content' }"
            >
            </common-table>
          </a-tab-pane>
          <a-tab-pane key="2" tab="历史退单申请">
            <common-table
                :columns="thirdColumns"
                :dataSource="historyList"
                :scroll="{ x: 'max-content' }"
            >
            </common-table>
          </a-tab-pane>
        </a-tabs>
      </a-collapse-panel>
      <a-collapse-panel key="2">
        <template #header>
          <span class="title">2、登记工单</span>
        </template>
        <a-form
            ref="zendeskForm"
            :model="zendeskFormState"
            :rules="zendeskRules"
            :label-col="{span: 7}"
        >
          <a-row>
            <a-col :xs="24" :xl="8" :xxl="6" :md="12" :lg="12">
              <a-form-item ref="zendeskId" label="zendesk工单号" name="zendeskId">
                <a-input v-model:value="zendeskFormState.zendeskId" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :xl="8" :xxl="6" :md="12" :lg="12">
              <a-form-item ref="platform" label="退款平台" name="platform">
                <a-select v-model:value="zendeskFormState.platform">
                  <a-select-option value="paypal_express">paypal_express</a-select-option>
                  <a-select-option value="worldpay_cc">worldpay_cc</a-select-option>
                  <a-select-option value="affirm_gateway">affirm_gateway</a-select-option>
                  <a-select-option value="afterpay">afterpay</a-select-option>
                  <a-select-option value="adyen_cc">adyen_cc</a-select-option>
                  <a-select-option value="stripe_payments">stripe_payments</a-select-option>
                  <a-select-option value="其他银行卡账号">其他银行卡账号</a-select-option>
                  <a-select-option value="拒付无需退款">拒付无需退款</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :xl="8" :xxl="6" :md="12" :lg="12">
              <a-form-item ref="email" label="客户邮箱" name="email">
                <a-input  v-model:value="zendeskFormState.email" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :xl="8" :xxl="6" :md="12" :lg="12">
              <a-form-item ref="type" label="退款类型" name="type">
                <a-select v-model:value="zendeskFormState.type">
                  <a-select-option value="系统处理">系统处理</a-select-option>
                  <a-select-option value="人工处理">人工处理</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :xl="8" :xxl="6" :md="12" :lg="12">
              <a-form-item ref="reason" label="退款原因" name="reason">
                <a-cascader v-model:value="zendeskFormState.reason" :options="refundReason" placeholder="请选择退款原因" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :xl="8" :xxl="6" :md="12" :lg="12">
              <a-form-item ref="refundStatus" label="退款情况" name="refundStatus">
                <a-select v-model:value="zendeskFormState.refundStatus">
                  <a-select-option value="全额">全额</a-select-option>
                  <a-select-option value="部分">部分</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :xl="8" :xxl="6" :md="12" :lg="12">
              <a-form-item ref="deliveryStatus" label="妥投情况" name="deliveryStatus">
                <a-select v-model:value="zendeskFormState.deliveryStatus">
                  <a-select-option value="已妥投">已妥投</a-select-option>
                  <a-select-option value="未妥投">未妥投</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :xl="8" :xxl="6" :md="12" :lg="12">
              <a-form-item ref="memo" label="退款描述" name="memo">
                <a-textarea  v-model:value="zendeskFormState.memo" :auto-size="{ minRows: 1, maxRows: 3 }"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :xs="24" :xl="8" :xxl="6" :md="12" :lg="12">
              <a-form-item  ref="zendeskId" label="佐证材料" name="zendeskId">
                <upload-img :action="action" v-model:list="fileList"/>
<!--                <a-upload-->
<!--                    v-model:file-list="fileList"-->
<!--                    :multiple="true"-->
<!--                    :headers="headers"-->
<!--                    :action="action"-->
<!--                    list-type="picture-card"-->
<!--                    @preview="handlePreview"-->
<!--                    :before-upload="beforeUpload"-->
<!--                >-->
<!--                  <div>-->
<!--                    <plus-outlined />-->
<!--                    <div style="margin-top: 8px">上传</div>-->
<!--                  </div>-->
<!--                </a-upload>-->
<!--                <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">-->
<!--                  <img alt="example" style="width: 100%" :src="previewImage" />-->
<!--                </a-modal>-->
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-collapse-panel>
    </a-collapse>
      <a-row>
        <a-col :xs="24" :xl="24" :xxl="24" :md="24" :lg="24" style="display: flex;justify-content: space-evenly;z-index: 999">
          <n-affix
              :bottom="20"
              :trigger-bottom="60"
          >
            <a-button>取消</a-button>
            <a-popconfirm
                title="是否要申请退款？"
                ok-text="是"
                cancel-text="否"
                style="margin-left: 15px"
                @confirm="handleRefund"
            >
              <a-button type="primary" :loading="btnLoading" style="margin-left: 15px">申请退款</a-button>
            </a-popconfirm>
          </n-affix>
        </a-col>
      </a-row>
  </a-spin>
</template>
<script>
export default {
  name: 'orderStandardization-refund',
}
</script>
<script setup>
import { ref,reactive,onMounted,computed } from 'vue'
import _ from 'lodash'
import {useRoute} from "vue-router";
import CommonTable from "@/components/commonTable/index.vue";
import {getRefundCompute, getRefundHistory, getRefundInfo, RefundRequest} from "@/api/standard/refund.js";
import {firstColumns,euColumns,caColumns,usColumns,thirdColumns,refundReason,zendeskRules,rules} from "@utils/refundData.js";
import {message, notification, Upload} from "ant-design-vue";
import {apiBaseUrl} from "@utils/service/index.js";
import {getToken} from "@utils/storage.js";
import UploadImg from "@/components/upload/uploadImg.vue";
const action = ref(apiBaseUrl + 'sys/common/upload')
const headers = ref({
  "X-Access-Token":getToken()
})
const orderData = reactive({
  paymentNo:"",
  platform:"",
  createdAtGmt:""
})
const activeKey = ref(['1','2'])
const btnLoading = ref(false)
const tabKey = ref('1')
const loading = ref(false)
const formState = reactive({
  orderId:''
})
const zendeskFormState = reactive({
  zendeskId:'',
  reason:'',
  platform:'',
  type:'',
  email:'',
  refundStatus:'',
  deliveryStatus:'',
  memo:'',
})
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const fileList = ref([]);
const formRef = ref()
const zendeskForm = ref()
const route = useRoute()
const params = ref({})
const historyList = ref([])
const firstDataList = ref([])
const selectedRows = ref([])
const tableData = ref([])
const amountDetailComputeList = ref([])
const paramsList = ref([])
const columns = computed(()=>{
  if(firstDataList.value[0]?.site === 'US'){
    return usColumns
  }else if(firstDataList.value[0]?.site === 'CA'){
    return caColumns
  }else{
    return euColumns
  }
})
/**
 * 表头样式
 * @param e 选中行数据
 */
const handleSelectionChange = (e) => {
  selectedRows.value = e
  console.log(e,tableData.value)
  for (let i = 0; i < tableData.value.length; i++) {
    tableData.value[i].disabled = true
    for (let j = 0; j < e.length; j++) {
      if(tableData.value[i].productSkuItem.sku === e[j].productSkuItem.sku){
        tableData.value[i].disabled = false
        break;
      }else{
        tableData.value[i].disabled = true
      }
    }
  }
  // tableData.value.forEach(item => {
  //   e.forEach(e=>{
  //     if(item.productSkuItem.sku === e.productSkuItem.sku){
  //       item.disabled = false
  //     }else{
  //       item.disabled = true
  //     }
  //   })
  // })
}
/**
 * 表头样式
 * @param row 行数据
 * @param column 列数据
 * @param rowIndex 行索引
 * @param columnIndex 列索引
 * @returns {{backgroundColor: string, color: string, textAlign: string}} 样式对象
 */
const headerCellStyle = ({row, column, rowIndex, columnIndex}) => {
  let arr = ['登记数据','仓库sku&物流单号&数量','换货sku','退款sku金额','退款服务费']
  if(arr.includes(column.label)){
    return {
      backgroundColor: '#52a7dd',
      color: '#070707',
      textAlign: 'center'
    }
  }else{
    return {
      backgroundColor: '#ffffff',
      color: '#070707',
      textAlign: 'center'
    }
  }
}

/**
 * 获取退款历史数据
 * @returns {Promise<void>}
 */
const getRefundHistoryData = async () => {
  try{
    const res = await getRefundHistory({orderId:formState.orderId})
    historyList.value = res.result.records
  }catch(err){
    message.error(err)
  }
}
/**
 * 获取退款信息
 * @returns {Promise<void>}
 */
const getRefundInfoData = async () => {
  try{
    const res = await getRefundInfo({orderId:formState.orderId})
    params.value = res.result
    let arr = []
    arr.push({
      site:res.result.site,
      currency:res.result.currency,
      totalAmt:res.result.totalAmt,
      discountAmt:res.result.discountAmt,
      deliveryAmt:res.result.deliveryAmt,
      taxAmt:res.result.taxAmt,
      outputVat:res.result.outputVat,
      totalRefund:res.result.totalRefund,
      totalRemaining:res.result.totalRemaining,
    })
    firstDataList.value = arr
    orderData.paymentNo = res.result.paymentNo
    zendeskFormState.email = res.result.email
    orderData.platform = res.result.platform
    orderData.createdAtGmt = res.result.createdAtGmt
    tableData.value = res.result.orderDetails
    tableData.value.forEach(item => {
      item.disabled = true
      item.replaceSku = ''
      item.skuRefund = 0
      item.serviceRefund = 0
      item.totalNoTaxRefund = 0
      item.totalTaxRefund = 0
      item.restTaxItem = {
        federalTaxRefund:0,
        provincialTaxRefund:0,
        outputVatRefund:0
      }
      item.packageList = [{
        warehouse:'',
        saleOrderCode:'',
        qty:1,
      }]
      item.saleOrderOptions = []
      item.skuOptions = item.mappingList.map(mapping=>{
        return {value:mapping.warehouseSku}
      })
    })
  }catch (err){
    message.error(err)
  }
}
/**
 * 选择物流单号
 * @param value 仓库sku
 * @param row 行数据
 */
const onSelect = (value, row) => {
  row.saleOrderOptions = row.mappingList.find(mapping => {
    return mapping.warehouseSku = value
  }).saleOrderCodeAndQtyList.map(saleOrder => {
    return {value:saleOrder.saleOrderCode}
  })
}
const init = async () => {
  await getRefundHistoryData()
  await getRefundInfoData()
}
onMounted(async ()=>{
  try{
    loading.value = true
    formState.orderId = route.query.orderId
    await init()
  }catch(e){}finally{
    loading.value = false
  }
})

const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
/**
 * 上传文件预览
 * @param file 文件对象
 * @returns {Promise<void>}
 */
const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
}
/**
 * 上传文件限制
 * @param file
 * @returns {boolean|string}
 */
const beforeUpload = file => {
  if (!['image/jpeg','image/png','image/jpg','image/gif'].includes(file.type)) {
    message.error(`${file.name} is not a picture`);
  }
  return ['image/jpeg','image/png','image/jpg','image/gif'].includes(file.type) || Upload.LIST_IGNORE
}
/**
 * 提交退款申请
 * @returns {MessageType}
 */
const handleRefund = async () => {
  try{
    btnLoading.value = true
    if(selectedRows.value.length === 0){
      return message.error('请选择退款数据')
    }
    selectedRows.value.forEach(item => {
      item.packageList.forEach(packages => {
        for (let packagesKey in packages) {
          if(packages[packagesKey] === ""){
            if(packagesKey === 'warehouse'){
              throw message.error('请选择仓库sku')
            }else if(packagesKey ==='saleOrderCode'){
              throw message.error('请选择物流单号')
            }
          }
        }
      })
    })
    btnLoading.value = true
    const validate = await zendeskForm.value.validate()
    let form = zendeskFormState
    form.reason = form.reason.join(',')
    // 处理文件上传格式
    form.evidence = fileList.value.map(item => item.response.message).join(',')
    //处理data
    let data = {}
    data.refundOrder = {
      platform:orderData.platform,
      paymentNo:orderData.paymentNo,
      totalAmt:firstDataList.value[0].totalAmt,
      currency:firstDataList.value[0].currency,
    }
    data.refund = paramsList.value[0]
    data.refundDetailList = selectedRows.value.map(item => {
      return {
        sku:item.productSkuItem.sku,
        replaceSku:item.replaceSku,
        skuRefund:item.skuRefund,
        serviceRefund:item.serviceRefund,
        federalTaxRefund:item.restTaxItem.federalTaxRefund,
        provincialTaxRefund:item.restTaxItem.provincialTaxRefund,
        outputVatRefund:item.restTaxItem.outputVatRefund,
        totalTaxRefund:item.totalTaxRefund,
        totalNoTaxRefund:item.totalNoTaxRefund,
        pack:"",
        packageList:item.packageList
      }
    });
    data.refundDetailList.forEach(item => {
      item.packageList.forEach((pack, index) => {
        item.pack += `${pack.warehouse} & ${pack.saleOrderCode} * ${pack.qty}${item.packageList.length > (index + 1) ? '\n' : ''}`
      })
    })
    data.refundTicket = form
    data.refundTicket.orderId = formState.orderId
    const res = await RefundRequest(data)
    notification.success({
      message: `成功创建工单号${res.result}`,
    });
    setTimeout(()=>{
      zendeskForm.value.resetFields()
      init()
    },1000)
  }catch (err){
    btnLoading.value = false
  }finally{
    btnLoading.value = false
  }
}
/**
 * 添加输入框
 * @param index 索引
 */
const addInput = (index) => {
  tableData.value[index].packageList.push({
    warehouse:'',
    saleOrderCode:'',
    qty:1,
  })
}
/**
 * 删除输入框
 * @param tableIndex 表格索引
 * @param listIndex 列表索引
 */
const deleteInput = (tableIndex,listIndex) => {
  tableData.value[tableIndex].packageList.splice(listIndex,1)
}
/**
 * 计算退款金额
 * @param item 行数据
 */
//设置防抖
const changeNum = _.debounce(async (items) => {
  console.log(selectedRows.value)
  let param = {
    ...params.value,
    ...firstDataList.value[0],
    amountDetailComputeList:selectedRows.value.map(item=>{
      return {
        ...item,
        ...item.productSkuItem,
        ...item.priceItem,
        ...item.outputItem,
        ...item.refundItem,
        ...item.serviceItem,
        ...item.settlementAccountItem,
        ...item.restTaxItem,
      }
    })
  }
  const res = await getRefundCompute(param)
  amountDetailComputeList.value = res.result.amountDetailComputeList
  delete res.result.amountDetailComputeList;
  //当前行的税对象赋值



  selectedRows.value.forEach(item=>{
    amountDetailComputeList.value.forEach(items=>{
      if(item.productSkuItem.sku === items.sku){
        item.restTaxItem = {
          federalTaxRefund:items.federalTaxRefund,
          provincialTaxRefund:items.provincialTaxRefund,
          outputVatRefund:items.outputVatRefund
        }
        item.totalNoTaxRefund = items.totalNoTaxRefund
        item.totalTaxRefund = items.totalTaxRefund
      }
    })
  })
  paramsList.value = [res.result]
},1000)
</script>
<style scoped>
.title{
  font-weight: bold;
  font-size: 16px;
}
.btn{
  position:fixed;
  bottom:10px;
  display: flex;
  margin-left: 35%;
  width:100%;
}
:deep(.el-table) {
  --el-table-row-hover-bg-color: #E4F7FF;
}
:deep(.el-table-column--selection){
  text-align: center;
}

</style>
